<?php
namespace App\Http\Middleware;

use Closure;

class AfterRequest{

    /**
     * 执行接口之后执行
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next){
	    $response = $next($request);
	    
	    // 获取错误码
	    $code = (string)$response->getStatusCode();
	    if($code == '422'){
		    if (isset($response->exception)) {
			    $errors = $response->exception->validator->errors();
			    $msg = json_decode(json_encode($errors));
			    foreach ($msg as $key => $item) {
				    $desc = $item[0];
			    }
		    } else {
			    $errors = @json_decode($response->getContent());
			    if ($errors && json_last_error() === JSON_ERROR_NONE) {
				    $errors = $errors;
			    }
		    }
		    $back['code'] = (string)$code;
		    $back['desc'] = $desc;
		    $back['errors'] = $errors;
		    header('Content-Type:application/json; charset=utf-8');
		    exit(json_encode($back,JSON_UNESCAPED_UNICODE));
	    }
		
		return $response;
    }
}
